package org.cuit.lmq.controller;

import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.cuit.lmq.constants.enums.FileTypeEnum;
import org.cuit.lmq.domain.common.BaseContextHolder;
import org.cuit.lmq.domain.common.Result;
import org.cuit.lmq.domain.po.SystemFile;
import org.cuit.lmq.domain.po.User;
import org.cuit.lmq.exception.CustomException;
import org.cuit.lmq.service.SystemFileService;
import org.cuit.lmq.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @author Seon
 * @date 2023/3/5
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class SystemFileController {

    @Value("${pingpang_system.separator}")
    private String separator;

    @Value("${pingpang_system.picture-prefix}")
    private String picturePrefix;

    @Value("${pingpang_system.mapping}")
    private String mappingPath;

    @Autowired
    private SystemFileService systemFileService;

    @Autowired
    private UserService userService;



    @GetMapping("/photo/wall")
    public Result<?> getPhotoWallURL() {
        long userId = BaseContextHolder.getCurrentUserId();
        LambdaQueryWrapper<SystemFile> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SystemFile::getForeignId, userId);
        wrapper.eq(SystemFile::getType, FileTypeEnum.PHOTO);

        SystemFile one = systemFileService.getOne(wrapper);
        if (StringUtils.isBlank(one.getFilePath())) {
            return Result.fail("你还暂时没有照片墙哦，快上传一张个性照片吧", 0);
        } else {
            return Result.success(one.getFilePath());
        }
    }

    @Deprecated
    @GetMapping("/download")
    public void download(@RequestParam("id") Long id, HttpServletResponse response) {
        SystemFile sysFile = systemFileService.getById(id);
        try {
            File testFile = new File(sysFile.getFilePath());
            if (!testFile.exists()) {
                throw new CustomException("文件不存在");
            }
            response.setContentType("multipart/form-data");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + new String(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8), "ISO8859-1") + "\"");
            @Cleanup FileInputStream is = new FileInputStream(sysFile.getFilePath());
            @Cleanup ServletOutputStream os = response.getOutputStream();
            IoUtil.copy(is, os);
            log.info("下载文件成功, fileId = {}", id);
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new CustomException("下载失败,文件已损坏");
        }
    }


    /**
     * 文件上传，只上传一个
     *
     * @param file 文件二进制流
     * @return
     */
    @PostMapping("/upload")
    public Result<?> upload(MultipartFile file, @RequestParam("type") FileTypeEnum type) {
        String child = FileTypeEnum.AVATAR.equals(type)? "/avatar/": "/photo/";
        // /photo/    ./file_base64

        Long userId = BaseContextHolder.getCurrentUserId();
        String filename = file.getOriginalFilename();
        String suffix = filename.substring(filename.indexOf("."));
        String uuid = UUID.randomUUID().toString();
        // 这里已经拿到了处理好的头像的文件名
        String finalName = uuid + suffix;

        try {
//            String basePath = ResourceUtils.getURL("classpath:").getPath();\
            File baseFile = new File(mappingPath);

            // 等下试一下这个东西
            File upload = new File(baseFile.getAbsolutePath(), child);
            if (!upload.exists()) {
                boolean mkdirs = upload.mkdirs();
            }
            file.transferTo(new File(upload + separator + finalName));

            String fileURL =  picturePrefix + child + finalName;

            LambdaQueryWrapper<SystemFile> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SystemFile::getForeignId, userId);
            wrapper.eq(SystemFile::getType, type);

            SystemFile one = systemFileService.getOne(wrapper);

            if (ObjectUtils.isNull(one)) {
                one = SystemFile.builder()
                        .foreignId(userId)
                        .filePath(fileURL)
                        .type(type)
                        .build();
            } else {
                one.setFilePath(fileURL);
            }
            systemFileService.saveOrUpdate(one);
            if (FileTypeEnum.AVATAR.equals(type)) {
                User user = userService.getById(userId);
                user.setAvatar(fileURL);
                userService.updateById(user);
            }
            log.info("用户" + userId + ", 已上传文件" + upload + separator + finalName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success(finalName);
    }
}
